
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.edu.hre.common.CurrentUserInfo;
import com.edu.hre.common.encrypt.Encrypter;
import com.edu.hre.db.dao.EmpDependentDAO;
import com.edu.hre.db.dao.LoginDAO;
import com.edu.hre.db.dto.HreEmpDependent;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

/**
 * Servlet implementation class Login
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Login() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=UTF-8");
		String userName = request.getParameter("username");
		String password = request.getParameter("password");
		CurrentUserInfo userInfo = Authenticate(userName, password);
		JsonObject myObj = new JsonObject();
		myObj.addProperty("isValid", userInfo.isValid());
		myObj.addProperty("userId", userInfo.getUserId());
		myObj.addProperty("userShortName", userInfo.getUserShortName());
		myObj.addProperty("userRoleId", userInfo.getUserRoleId());
		myObj.addProperty("userSubUnitId", userInfo.getUserSubUnitId());
		myObj.addProperty("userIdSurvey", userInfo.getUserIdSurvey());
		myObj.addProperty("canViewEmployeeList", userInfo.isCanViewEmployee());
		myObj.addProperty("canViewChartResource", userInfo.isCanViewChartResouce());
		myObj.addProperty("canViewChartLeave", userInfo.isCanViewChartLeave());
		response.getWriter().println(myObj.toString());
		response.getWriter().close();

	}

	private CurrentUserInfo Authenticate(String userName, String password)
			throws UnsupportedEncodingException {
		// TODO Auto-n` method stub
		return new LoginDAO().ValidateLogin(userName,
				Encrypter.encodeMD5(password));

	}

}
